package com.sumer.psychology.space.infrastructure.persistence.mongo;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.sumer.psychology.common.persistence.mongodb.AbstractMongoRepository;

import java.util.UUID;

/**
 * mongo消息资源库
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/11/5
 * Time: 9:42
 */
public abstract class MongoMessageRepository extends AbstractMongoRepository {
    private static final String DB_NAME = "sumer_message";

    @Override
    protected String dbName() {
        return DB_NAME;
    }

    /**
     * 增加一条消息
     *
     * @param data data
     */
    public abstract void add(String data);

    /**
     * 统一更新
     *
     * @param host    host
     * @param message message
     */
    protected void update(DBObject host, DBObject message) {
        if (!message.containsField("messageId") || message.get("messageId") == null) {
            message.put("messageId", UUID.randomUUID().toString());
        }

        db().getCollection(dbName()).update(
                host,
                new BasicDBObject("$push", new BasicDBObject("messages", message)),
                true,
                false);
    }
}

